<template>
  <div style="float: right; margin-top: 10px; margin-right: 20px">
    <!-- 顶部新增按钮 -->
    <el-button
      type="primary"
      size="small"
      @click=";(type = 'create'), (dialogFormVisible = true)"
      style="margin-right: 10px"
    >
      <el-icon>
        <Plus />
      </el-icon>
      <span>新增</span>
    </el-button>
    <el-button type="danger" size="small" @click="handleDletePeopleAll">
      <el-icon>
        <Delete />
      </el-icon>
      <span>删除</span>
    </el-button>
    <el-button type="primary" size="small" @click="exportFile">
      <el-icon>
        <FolderOpened />
      </el-icon>
      <span>导出</span>
    </el-button>
    <el-button type="primary" size="small" @click="handleprint">
      <el-icon>
        <Printer />
      </el-icon>
      <span>打印</span>
    </el-button>
  </div>
  <div
    class="borrApplication"
    style="float: left; width: 100%; height: calc(100% - 54px)"
  >
    <div class="common-layout" style="height: 100%">
      <el-container style="height: 100%">
        <!-- 头部 -->
        <el-header>
          <div class="inquire">
            <span>借用单号</span>
            <el-input
              v-model="input1"
              class="w-50 m-2"
              size="small"
              clearable
            />
            <span>日期</span>
            <el-date-picker
              v-model="value"
              type="daterange"
              size="small"
              start-placeholder="Start date"
              end-placeholder="End date"
            />
            <span>借用类型</span>
            <el-input
              v-model="input2"
              class="w-50 m-2"
              size="small"
              clearable
            />
            <el-button
              type="primary"
              size="small"
              @click="handlinquire"
              @keydown.enter="keydown()"
              style="margin-left: 10px"
              >查询</el-button
            >
          </div>
        </el-header>
        <!-- 新增弹出框 -->
        <el-dialog
          v-model="dialogFormVisible"
          title="入库新增"
          width="30%"
          center
          :before-close="handleClose"
        >
          <el-form
            :model="form"
            class="el-form"
            :rules="rules"
            ref="xiongerRef"
          >
            <el-form-item label="借用单号" required prop="borOrder">
              <el-input v-model="form.borOrder" />
            </el-form-item>
            <el-form-item label="日期" required prop="borDate">
              <el-input v-model="form.borDate" />
            </el-form-item>
            <el-form-item label="借用类型" required prop="borType">
              <el-input v-model="form.borType" />
            </el-form-item>
            <el-form-item label="项目名称" required prop="projectName">
              <el-input v-model="form.projectName" />
            </el-form-item>
            <el-form-item label="借用人" required prop="userName">
              <el-input v-model="form.userName" />
            </el-form-item>
            <el-form-item label="联系电话" required prop="phone">
              <el-input v-model="form.phone" />
            </el-form-item>
            <el-form-item label="部门" required prop="department">
              <el-input v-model="form.department" />
            </el-form-item>
            <el-form-item label="仓库名称" required prop="storeName">
              <el-input v-model="form.storeName" />
            </el-form-item>
            <el-form-item label="编码" required prop="materialNumber">
              <el-input v-model="form.materialNumber" />
            </el-form-item>
            <el-form-item label="名称" required prop="materialName">
              <el-input v-model="form.materialName" />
            </el-form-item>
            <el-form-item label="简拼码" required prop="materialSpelling">
              <el-input v-model="form.materialSpelling" />
            </el-form-item>
            <el-form-item label="类别" required prop="materialClass">
              <el-input v-model="form.materialClass" />
            </el-form-item>
            <el-form-item
              label="规格型号"
              required
              prop="materialSpecificationModel"
            >
              <el-input v-model="form.materialSpecificationModel" />
            </el-form-item>
            <el-form-item label="单位" required prop="materialUnit">
              <el-input v-model="form.materialUnit" />
            </el-form-item>
            <el-form-item label="现有价值" required prop="materialPrice">
              <el-input v-model="form.materialPrice" />
            </el-form-item>
            <el-form-item label="数量" required prop="materialInventory">
              <el-input v-model="form.materialInventory" />
            </el-form-item>
            <el-form-item label="金额" prop="materialWorth">
              <el-input v-model="form.materialWorth" disabled />
            </el-form-item>
            <el-form-item label="借用用途" required prop="borUse">
              <el-input v-model="form.borUse" />
            </el-form-item>
            <el-form-item label="借用状态" required prop="borState">
              <el-input v-model="form.borState" />
            </el-form-item>
            <el-form-item label="预归还日期" required prop="preReturnDate">
              <el-input v-model="form.preReturnDate" />
            </el-form-item>
            <el-form-item label="经办人" required prop="operator">
              <el-input v-model="form.operator" />
            </el-form-item>
            <el-form-item label="备注" required prop="remarks">
              <el-input v-model="form.remarks" />
            </el-form-item>
            <el-form-item label="审批结果" required prop="approved">
              <el-input v-model="form.approved" />
            </el-form-item>
            <el-form-item label="审批人" prop="approvers">
              <el-input v-model="form.approvers" />
            </el-form-item>
            <el-form-item label="归还日期" required prop="setLastUpdate">
              <el-input v-model="form.setLastUpdate" />
            </el-form-item>
            <el-form-item label="归还数量" required prop="quantity">
              <el-input v-model="form.quantity" />
            </el-form-item>
            <el-form-item label="未归还数量" required prop="unreturned">
              <el-input v-model="form.unreturned" />
            </el-form-item>
            <el-form-item
              label="未归还说明"
              required
              prop="doesNotAccessMemory"
            >
              <el-input v-model="form.doesNotAccessMemory" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">
              <el-button
                v-if="type === 'create'"
                type="primary"
                @click="submitAndExit"
              >
                新增并退出
              </el-button>
              <el-button
                v-else-if="type === 'update'"
                type="primary"
                @click="setAndExit"
              >
                修改并退出
              </el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 下半部分 -->
        <el-container>
          <!-- 侧边栏 -->
          <el-aside width="200px">
            <div class="left demo-collapse">
              <el-collapse v-model="activeNames">
                <div class="state">
                  <el-button type="info" round @click="handleexpand"
                    >展开</el-button
                  >
                  <el-button type="info" round @click="handlecontract"
                    >收缩</el-button
                  >
                </div>
                <el-collapse-item title="借用状态" name="1">
                  <div @click="handlesearch">
                    <div>全部</div>
                    <div>
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>正常</span>
                    </div>
                    <div>
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>异常</span>
                    </div>
                    <div>
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>锁定</span>
                    </div>
                    <div>
                      <el-icon>
                        <Document />
                      </el-icon>
                      <span>审核</span>
                    </div>
                  </div>
                </el-collapse-item>
              </el-collapse>
            </div>
          </el-aside>
          <!-- 主要部分 -->
          <el-container>
            <el-main>
              <el-table
                ref="multipleTableRef"
                :data="borrapplication"
                style="width: 100%; height: 100%"
                :cell-style="{ textAlign: 'center' }"
                :header-cell-style="{ 'text-align': 'center' }"
              >
                <el-table-column type="selection" width="55" />
                <el-table-column label="操作" width="200px">
                  <template #default="scope">
                    <el-button
                      type="danger"
                      size="small"
                      @click="handleRemove(scope.row)"
                      >删除</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="setOpendialogVisible(scope.row)"
                      >修改</el-button
                    >
                    <el-button
                      type="primary"
                      size="small"
                      @click="oncheck(scope.row)"
                      >查看</el-button
                    >
                  </template>
                </el-table-column>
                <el-table-column prop="borOrder" label="借用单号" width="120" />
                <el-table-column prop="borDate" label="日期" width="120" />
                <el-table-column prop="borType" label="借用类型" width="120" />
                <el-table-column
                  prop="projectName"
                  label="项目名称"
                  width="150"
                />
                <el-table-column prop="userName" label="借用人" width="120" />
                <el-table-column prop="phone" label="联系电话" width="120" />
                <el-table-column prop="department" label="部门" width="120" />
                <el-table-column
                  prop="storeName"
                  label="仓库名称"
                  width="120"
                />
                <el-table-column
                  prop="materialNumber"
                  label="编码"
                  width="120"
                />
                <el-table-column prop="materialName" label="名称" width="120" />
                <el-table-column
                  prop="materialSpelling"
                  label="简拼码"
                  width="120"
                />
                <el-table-column
                  prop="materialClass"
                  label="类别"
                  width="150"
                />
                <el-table-column
                  prop="materialSpecificationModel"
                  label="规格型号"
                  width="120"
                />
                <el-table-column prop="materialUnit" label="单位" width="120" />
                <el-table-column
                  prop="materialPrice"
                  label="现有价值"
                  width="120"
                />
                <el-table-column
                  prop="materialInventory"
                  label="数量"
                  width="120"
                />
                <el-table-column
                  prop="materialWorth"
                  label="金额"
                  width="120"
                />
                <el-table-column prop="borUse" label="借用用途" width="120" />
                <el-table-column prop="borState" label="借用状态" width="120" />
                <el-table-column
                  prop="preReturnDate"
                  label="预归还日期"
                  width="120"
                />
                <el-table-column prop="operator" label="经办人" width="120" />
                <el-table-column prop="remarks" label="备注" width="120" />
                <el-table-column prop="approved" label="审批结果" width="150" />
                <el-table-column prop="approvers" label="审批人" width="120" />
                <el-table-column
                  prop="setLastUpdate"
                  label="归还日期"
                  width="120"
                />
                <el-table-column prop="quantity" label="归还数量" width="120" />
                <el-table-column
                  prop="unreturned"
                  label="未归还数量"
                  width="120"
                />
                <el-table-column
                  prop="doesNotAccessMemory"
                  label="未归还说明"
                  width="120"
                />
              </el-table>
            </el-main>
            <el-footer>
              <div class="demo-pagination-block">
                <el-pagination
                  v-model:current-page="currentPage4"
                  v-model:page-size="pageSize4"
                  :page-sizes="[10, 20, 30, 40]"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                />
              </div>
            </el-footer>
          </el-container>
        </el-container>
      </el-container>
    </div>
  </div>
  <!-- 查看弹出框 -->
  <el-dialog
    v-model="dialogTableVisible"
    align-center
    title="详细信息"
    width="90%"
  >
    <el-table :data="form">
      <el-table-column prop="borOrder" label="借用单号" width="120" />
      <el-table-column prop="borDate" label="日期" width="120" />
      <el-table-column prop="borType" label="借用类型" width="120" />
      <el-table-column prop="projectName" label="项目名称" width="150" />
      <el-table-column prop="userName" label="借用人" width="120" />
      <el-table-column prop="phone" label="联系电话" width="120" />
      <el-table-column prop="department" label="部门" width="120" />
      <el-table-column prop="storeName" label="仓库名称" width="120" />
      <el-table-column prop="materialNumber" label="编码" width="120" />
      <el-table-column prop="materialName" label="名称" width="120" />
      <el-table-column prop="materialSpelling" label="简拼码" width="120" />
      <el-table-column prop="materialClass" label="类别" width="150" />
      <el-table-column
        prop="materialSpecificationModel"
        label="规格型号"
        width="120"
      />
      <el-table-column prop="materialUnit" label="单位" width="120" />
      <el-table-column prop="materialPrice" label="现有价值" width="120" />
      <el-table-column prop="materialInventory" label="数量" width="120" />
      <el-table-column prop="materialWorth" label="金额" width="120" />
      <el-table-column prop="borUse" label="借用用途" width="120" />
      <el-table-column prop="borState" label="借用状态" width="120" />
      <el-table-column prop="preReturnDate" label="预归还日期" width="120" />
      <el-table-column prop="operator" label="经办人" width="120" />
      <el-table-column prop="remarks" label="备注" width="120" />
      <el-table-column prop="approved" label="审批结果" width="150" />
      <el-table-column prop="approvers" label="审批人" width="120" />
      <el-table-column prop="setLastUpdate" label="归还日期" width="120" />
      <el-table-column prop="quantity" label="归还数量" width="120" />
      <el-table-column prop="unreturned" label="未归还数量" width="120" />
      <el-table-column
        prop="doesNotAccessMemory"
        label="未归还说明"
        width="120"
      />
    </el-table>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, onMounted, onUnmounted } from 'vue'
import {
  getMaterialInfo,
  addMaterialInfo,
  deleteMaterialInfo,
  setMaterialInfo,
  dletematerialall,
} from '../../api/getapi'
import { ElMessage, ElMessageBox } from 'element-plus'
import { utils, writeFileXLSX } from 'xlsx'
// 增、改 按钮当前状态
const type = ref<string>('create')
//新增
const xiongerRef = ref(null)
const form = ref<any>({
  borOrder: '',
  borDate: '',
  borType: '',
  projectName: '',
  userName: '',
  phone: '',
  department: '',
  storeName: '',
  materialNumber: '',
  materialName: '',
  materialSpelling: '',
  materialClass: '',
  materialSpecificationModel: '',
  materialUnit: '',
  materialPrice: '',
  materialInventory: '',
  materialWorth: '',
  borUse: '',
  borState: '',
  preReturnDate: '',
  operator: '',
  remarks: '',
  approved: '',
  approvers: '',
  setLastUpdate: '',
  quantity: '',
  unreturned: '',
  doesNotAccessMemory: '',
})

const dialogFormVisible = ref(false)
const handleClose = (done: () => void) => {
  ElMessageBox.confirm('确认关闭吗？关闭后无法保存信息！')
    .then(() => {
      done()
    })
    .catch(() => {
      // catch error
    })
}

// 新增提交
const submitAndExit = async () => {
  // console.log(xiongerRef.value)
  const result = await xiongerRef.value?.validate()
  console.log(result)
  try {
    const forData = form.value
    form.value.materialWorth =
      form.value.materialPrice * form.value.materialInventory
    // console.log(form.value.materialWorth)
    // console.log('fordata', forData)
    const result = await addMaterialInfo(forData)
    console.log('添加', result)
    form.value = {}
    dialogFormVisible.value = false
    ElMessage({
      message: '添加成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    ElMessage({
      message: '材料编码重复',
      type: 'error',
      duration: 1500,
      showClose: true,
    })
  }
  getgg()
}
// 校验表单
const rules = {
  borOrder: [{ required: true, message: '借用单号必填!' }],
  borDate: [{ required: true, message: '日期必填!' }],
  borType: [{ required: true, message: '借用类型必填!' }],
  projectName: [{ required: true, message: '项目名称必填!' }],
  userName: [{ required: true, message: '借用人必填!' }],
  phone: [{ required: true, message: '联系电话必填!' }],
  department: [{ required: true, message: '部门必填!' }],
  storeName: [{ required: true, message: '仓库名称必填!' }],
  materialNumber: [{ required: true, message: '编码必填!' }],
  materialName: [{ required: true, message: '名称必填!' }],
  materialSpelling: [{ required: true, message: '简拼码必填!' }],
  materialClass: [{ required: true, message: '类别必填!' }],
  materialSpecificationModel: [{ required: true, message: '规格型号必填!' }],
  materialUnit: [{ required: true, message: '单位必填!' }],
  materialPrice: [{ required: true, message: '现有价值必填!' }],
  materialInventory: [{ required: true, message: '数量必填!' }],
  materialWorth: [{ required: false, message: '金额必填!' }],
  borUse: [{ required: true, message: '借用用途必填!' }],
  borState: [{ required: true, message: '借用状态必填!' }],
  preReturnDate: [{ required: true, message: '预归还日期必填!' }],
  operator: [{ required: true, message: '经办人必填!' }],
  remarks: [{ required: true, message: '备注必填!' }],
  approved: [{ required: true, message: '审批结果必填!' }],
  approvers: [{ required: true, message: '审批人必填!' }],
  setLastUpdate: [{ required: true, message: '归还日期必填!' }],
  quantity: [{ required: true, message: '归还数量必填!' }],
  unreturned: [{ required: true, message: '未归还数量必填!' }],
  doesNotAccessMemory: [{ required: true, message: '未归还说明必填!' }],
}
//表格数据
let borrapplication = ref<ProjectInfo[]>([])
const multipleTableRef = ref<any>()
const total = ref()
//分页器数据
const currentPage4 = ref(1)
const pageSize4 = ref(10)

const allData = ref<any>()

//渲染数据
const show = () => {
  borrapplication.value = allData.value.slice(
    pageSize4.value * (currentPage4.value - 1),
    pageSize4.value * currentPage4.value,
  )
}

watch([currentPage4, pageSize4], (val) => {
  console.log('new val', val)
  show()
})

//表格获取数据
const getgg = async () => {
  try {
    const result = await getMaterialInfo()
    console.log(result)

    allData.value = result
    total.value = allData.value.length
    show()
  } catch (error) {
    console.log('请求出错', error)
  }
}
getgg()
// 导出
function exportFile() {
  const data = multipleTableRef.value.getSelectionRows()
  // console.log('选中数据:', data)

  const ws = utils.json_to_sheet(data)
  const wb = utils.book_new()
  utils.book_append_sheet(wb, ws, '项目信息')
  writeFileXLSX(wb, 'SheetJSVueAoO.xlsx')
}
// 多项删除or删除所选
const handleDletePeopleAll = async () => {
  const data = multipleTableRef.value.getSelectionRows()
  console.log('选中数据:', data) //数组
  const result = await dletematerialall(data)
  console.log(result)
  // 返回修改后的数组赋值给表格
  borrapplication.value = result
}
// 打印按钮
const handleprint = () => {
  console.log('打印')
}
//侧边栏展开收缩
let activeNames = ref(['1'])
const handleexpand = () => {
  activeNames.value = ['1']
}
const handlecontract = () => {
  activeNames.value = []
}
//搜索框数据
const input1 = ref('')
const value = ref('')
const input2 = ref('')
const handlinquire = () => {
  let obj: any = {
    borOrder: input1.value,
    borType: input2.value,
  }

  // 排除空
  for (let key in obj) {
    if (obj[key] == '' || obj[key] == null) {
      delete obj[key]
    }
  }
  /*condition--搜索条件（obj）   data--被筛选的数据--arr  */
  let filter = (condition: any, data: any) => {
    return data.filter((item: any) => {
      return Object.keys(condition).every((key) => {
        return String(item[key]).includes(String(condition[key]).trim())
      })
    })
  }
  borrapplication.value = filter(obj, allData.value)
  if (value.value) {
    borrapplication.value = borrapplication.value.filter((item) => {
      return (
        new Date(item.borDate).getTime() > new Date(value.value[0]).getTime() &&
        new Date(item.borDate).getTime() < new Date(value.value[1]).getTime()
      )
    })
  }
  if (borrapplication.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '没有相关信息',
    })
  }
}
// 回车搜索

const keyDown: any = (e: { keyCode: number }) => {
  if (e.keyCode == 13 || e.keyCode == 108) {
    handlinquire()
  }
}

onMounted(() => {
  //绑定监听事件
  window.addEventListener('keydown', keyDown)
})

onUnmounted(() => {
  //销毁事件
  window.removeEventListener('keydown', keyDown, false)
})
//侧边栏搜索
const handlesearch = (e: any) => {
  if (e.target.innerHTML == '全部') {
    borrapplication.value = allData.value
  } else {
    borrapplication.value = allData.value.filter((item: any) => {
      return item.borState?.includes(e.target.innerHTML)
    })
  }
  if (borrapplication.value.length == 0) {
    ElMessage({
      type: 'error',
      message: '没有相关信息',
    })
  }
}
//表格删除数据
const handleRemove = async (prod: any) => {
  try {
    const result = await deleteMaterialInfo(prod)
    borrapplication.value = result
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 1500,
    })
  } catch (error) {
    console.log(error)
  }
}
//表格修改数据
const setOpendialogVisible = (prod: any) => {
  type.value = 'update'
  console.log('修改的', prod)
  dialogFormVisible.value = true
  form.value = prod
}
// 修改并退出
const setAndExit = async () => {
  form.value.materialWorth =
    form.value.materialPrice * form.value.materialInventory
  const result = await setMaterialInfo(form.value)
  console.log('后端返回的', result)
  //清空表单
  form.value = {}
  // 关闭表单
  dialogFormVisible.value = false
  // 返回修改后的数组赋值给表格
  borrapplication.value = result
  ElMessage({
    message: '修改成功',
    type: 'success',
    duration: 1500,
  })
}

//表格查看数据
// 查看弹出框的状态
const dialogTableVisible = ref(false)
const oncheck = (prod: any) => {
  // type.value = ''
  dialogTableVisible.value = true
  const arr = []
  arr.push(prod)
  form.value = arr
}
</script>

<style lang="scss" scoped>
//头部
.topheader {
  line-height: 28px;
  height: 28px;
  width: 100%;
  margin-bottom: 0px;
}

// 搜索
.demo-date-picker {
  display: flex;
  width: 300px;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.inquire {
  display: flex;
  justify-content: space-evenly;
  align-items: center;
  width: 1000px;
  height: 28px;
  margin-top: 0px;

  span {
    font-size: 15px;
    margin: 0 10px;
  }

  .w-50 {
    width: 150px;
  }

  el-button {
    vertical-align: middle;
  }
}

//侧边栏
.el-aside {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.left {
  height: 100%;
  background-color: #fff;
  padding-top: 20px;
}

.el-collapse-item {
  padding: 0px 20px;
  cursor: pointer;
}

.el-icon {
  vertical-align: middle;
}

//表格样式
:deep(.el-scrollbar) {
  background-color: #fff;
}
</style>
